﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace EIA.SLClient.Utility.Controls
{
    public partial class SelectableTreeControl : UserControl
    {
        public SelectableTreeControl()
        {
            // 为初始化变量所必需
            InitializeComponent();
            this.Loaded += (s, e) =>
            {
                AsyncUtils.DelayExcuteOnUIDispatcher(() =>
                {
                    InitialExpend();
                    AsyncUtils.DelayExcuteOnUIDispatcher(() =>
                    {
                        SetVisualSelectItem();
                    }, 100);
                }, 100);
            };
        }

        private void InitialExpend()
        {
            int newValue = this.ExpendDepth;
            if (this.RootNodes != null)
            {
                this.TreeViewMain.ExpandToDepth(newValue);
            }
        }

        private void SetVisualSelectItem()
        {
            if (this.TreeViewMain.SelectedItem != SelectedNode)
            {
                if (SelectedNode == null) this.TreeViewMain.ClearSelection();
                else this.TreeViewMain.SelectItem(SelectedNode);
            }
        }

        #region RootNodes (DependencyProperty)

        /// <summary>
        /// 根节点集合
        /// </summary>
        public ObservableCollection<TreeNode> RootNodes
        {
            get { return (ObservableCollection<TreeNode>)GetValue(RootNodesProperty); }
            set { SetValue(RootNodesProperty, value); }
        }
        public static readonly DependencyProperty RootNodesProperty =
            DependencyProperty.Register("RootNodes", typeof(ObservableCollection<TreeNode>), typeof(SelectableTreeControl),
            new PropertyMetadata(new ObservableCollection<TreeNode>(), new PropertyChangedCallback(OnRootNodesChanged)));

        private static void OnRootNodesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            // 获取自身的引用
            SelectableTreeControl source = (SelectableTreeControl)sender;

            // 处理逻辑
            ObservableCollection<TreeNode> newValue = (ObservableCollection<TreeNode>)args.NewValue;
            source.TreeViewMain.ItemsSource = newValue;

            AsyncUtils.DelayExcuteOnUIDispatcher(() =>
            {
                source.InitialExpend();
            }, 100);
        }

        #endregion

        #region ExpendDepth (DependencyProperty)

        /// <summary>
        /// 该依赖属性的描述
        /// </summary>
        public int ExpendDepth
        {
            get { return (int)GetValue(ExpendDepthProperty); }
            set { SetValue(ExpendDepthProperty, value); }
        }
        public static readonly DependencyProperty ExpendDepthProperty =
            DependencyProperty.Register("ExpendDepth", typeof(int), typeof(SelectableTreeControl),
            new PropertyMetadata(0, new PropertyChangedCallback(OnExpendDepthChanged)));

        private static void OnExpendDepthChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            // 获取自身的引用
            SelectableTreeControl source = (SelectableTreeControl)sender;

            // 处理逻辑
            int newValue = (int)args.NewValue;
            source.InitialExpend();
        }

        #endregion

        #region SelectedNode (DependencyProperty)

        /// <summary>
        /// 选中的节点
        /// </summary>
        public TreeNode SelectedNode
        {
            get { return (TreeNode)GetValue(SelectedNodeProperty); }
            set { SetValue(SelectedNodeProperty, value); }
        }
        public static readonly DependencyProperty SelectedNodeProperty =
            DependencyProperty.Register("SelectedNode", typeof(TreeNode), typeof(SelectableTreeControl),
            new PropertyMetadata(null, new PropertyChangedCallback(OnSelectedNodeChanged)));

        private static void OnSelectedNodeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            // 获取自身的引用
            SelectableTreeControl source = (SelectableTreeControl)sender;

            // 处理逻辑
            TreeNode newValue = (TreeNode)args.NewValue;
            TreeNode oldValue = (TreeNode)args.OldValue;

            source.SetVisualSelectItem();
            var data = (newValue != null ? newValue.Data : null);
            if (source.SelectedData != data)
            {
                source.SelectedData = data;
            }
        }

        #endregion

        #region SelectedData (DependencyProperty)

        /// <summary>
        /// 该依赖属性的描述
        /// </summary>
        public object SelectedData
        {
            get { return (object)GetValue(SelectedDataProperty); }
            set { SetValue(SelectedDataProperty, value); }
        }
        public static readonly DependencyProperty SelectedDataProperty =
            DependencyProperty.Register("SelectedData", typeof(object), typeof(SelectableTreeControl),
            new PropertyMetadata(null, new PropertyChangedCallback(OnSelectedDataChanged)));

        private static void OnSelectedDataChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            // 获取自身的引用
            SelectableTreeControl source = (SelectableTreeControl)sender;

            // 处理逻辑
            object newValue = (object)args.NewValue;


            if (newValue == null && source.SelectedNode == null) return;

            if (newValue == null)
            {
                source.SelectedNode = null;
            }
            else
            {
                if (source.SelectedNode != null && newValue.Equals(source.SelectedNode.Data)) return;
                TreeNode node = TreeNode.FindNode(source.RootNodes, newValue);
                source.SelectedNode = node;
            }
        }

        #endregion

        private void TreeViewMain_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void TreeViewMain_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (sender is TextBlock)
            {
                SelectedNode = (TreeNode)((sender as TextBlock).DataContext);
                //TreeViewMain.SelectItem(SelectedNode);
            }
            else
            {
                SelectedNode = null;
                //TreeViewMain.ClearSelection();
            }

        }

        private void TreeViewMain_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!(sender is TextBlock))
            {
                SelectedNode = null;
                //TreeViewMain.ClearSelection();
            }
        }

        private void TreeViewMain_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (_mouse_leaved) return;
            SelectedNode = e.NewValue as TreeNode;
        }

        bool _mouse_leaved = true;
        private void TreeViewMain_MouseLeave(object sender, MouseEventArgs e)
        {
            _mouse_leaved = true;
        }

        private void TreeViewMain_MouseEnter(object sender, MouseEventArgs e)
        {
            _mouse_leaved = false;
        }
    }
}